import sys
import struct
from bin_parser import BinParser, BinParseFunctions

class DexDataFunctions(BinParseFunctions):
    def stringData(self, data):
        #Skip the uleb128 length.
        l = 0
        while l < len(data) and ord(data[l]) > 0x7f:
            l = l + 1 
        return data[l+1:]

    def readSignedLeb128(self, data):
        count = 0
        data_len = len(data)
        result = 0
        signbit = -1
        while True:
            cur = ord(data[count:count+1])
            result = result | ((cur & 0x7f) << (count * 7))
            count = count + 1
            signbit = signbit << 7
            if not ((cur & 0x80) == 0x80 and count < 5 and count < data_len):
                break
        
        if ((signbit >> 1) & result):
            result = result | signbit

        data_ret = struct.pack('i', result)
        return data_ret, count 
           
    def readUnsignedLeb128(self, data):
        count = 0
        data_len = len(data)
        result = 0
        while True:
            cur = ord(data[count:count+1])
            result = result | ((cur & 0x7f) << (count * 7))
            count = count + 1
            if not ((cur & 0x80) == 0x80 and count < 5 and count < data_len):
                break
       
        data_ret = struct.pack('I', result)
        return data_ret, count 
       
        
